package cn.tit.ias.util.shiro;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter{
	@Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        
		// session域中获取正确验证码
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		String validateCode = (String) session.getAttribute("checkCode");
		System.out.println("session域中"+validateCode);
		//System.out.println(request.getAttribute("checkCode"));
		// 读取提交的验证码
		String requestData = request.getReader().readLine();
		// 将字符串转成json
//		ObjectMapper objectMapper = new ObjectMapper();
//		JsonNode node = objectMapper.readTree(requestData);
//		String submitCode = node.get("checkCode").asText().toUpperCase();
//		session.setAttribute("submitCode",submitCode);
//		System.out.println("提交的"+submitCode);
		String submitCode = request.getParameter("checkCode");
		System.out.println("提交的"+submitCode);
		 if(submitCode!=null && validateCode!=null && !submitCode.equals(validateCode)){
	            //如果校验失败，将验证码错误失败信息，通过shiroLoginFailure设置到request中
			 System.out.println("验证失败");
	            httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError");
	            //拒绝访问，不再校验账号和密码 
	            return true; 
	        }
		 	System.out.println("验证成功");
	        return super.onAccessDenied(request, response);
		
    }
}
